﻿using Mapster;
using Microsoft.EntityFrameworkCore;
using ShortLink.Common;
using ShortLink.Common.Helper;
using ShortLink.Common.Jwt;
using ShortLink.Common.Redis;
using ShortLink.Common.Results;
using SL_Account.DBContext;
using SL_Account.Models.Do;
using SL_Account.Models.Requests;
using SL_Account.Models.Vo;

namespace SL_Account.Services.Impl
{
    public class UserService : IUserService
    {
        private readonly IRedisAccessor redisAccessor;
        private readonly UserDBContext userDBContext;

        public UserService(IRedisAccessor redisAccessor, UserDBContext userDBContext)
        {
            this.redisAccessor = redisAccessor;
            this.userDBContext = userDBContext;
        }

        public async Task<JsonData> Login(UserLoginRequest request)
        {
        
            var u = userDBContext.Users.Where(u => u.Mail == request.Mail && u.Pwd == MD5Helper.ComputeMD5(request.Pwd)).Select(x => new UserDO { Mail = x.Mail, Username = x.Username, AccountNo = x.AccountNo }).FirstOrDefault();
            if (u is null) 
            {
                return JsonData.BuildError("用户邮箱或者密码不正确!");
            }
            var token  = JwtHelper.GetToken(new TokenModel { Mail = u.Mail, AccountNo = long.Parse(u.AccountNo.ToString()), Username = u.Username });

            return JsonData.BuildSuccess(token);
        }

        public async Task<JsonData> UserDetail()
        {
            var u = App.GetUser();
            var userDO = await userDBContext.Users.Where(x => x.Mail == u.Mail).FirstOrDefaultAsync();
            var vo = userDO.Adapt<UserVO>();
            return JsonData.BuildSuccess(vo);
        }

        public async Task<JsonData> UserRegister(UserRegisterRequest registerRequest)
        {
            var codeVal = await this.redisAccessor.GetAsync<string>(registerRequest.Mail);
            if (string.IsNullOrEmpty(codeVal) || !codeVal.Equals(registerRequest.Code)) 
            {
                return JsonData.BuildError("验证码无效!");
            }

            var userDO = registerRequest.Adapt<UserDO>();
            userDO.Pwd = MD5Helper.ComputeMD5(userDO.Pwd);
            //插入数据库
            await userDBContext.Users.AddAsync(userDO);
            await userDBContext.SaveChangesAsync();
            //发送Task 
            return JsonData.BuildSuccess("注册成功!");
        }
    }
}
